package com.nbsaas.nbmall.web.front;

import com.haoxuer.discover.web.controller.front.BaseController;
import com.nbsaas.nbmall.shop.api.apis.ShopApi;
import com.nbsaas.nbmall.shop.api.domain.response.ShopResponse;
import com.nbsaas.nbmall.shop.data.entity.Shop;
import net.sf.ehcache.Statistics;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.ehcache.EhCacheCache;
import org.springframework.cache.ehcache.EhCacheCacheManager;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Controller
public class WebController extends BaseController {


    @Autowired
    private ShopApi shopApi;

    @RequestMapping("index")
    public String index(){
        return redirect("login.htm");
    }

    @RequestMapping("bindShop")
    public String bindShop(String code, String state, Model model){
        try {
            ShopResponse response= shopApi.bind(code,state);
            model.addAttribute("msg",response.getMsg());
        }catch (Exception e){
            e.printStackTrace();
        }
        return getView("bindShop");
    }

    @Autowired
    private EhCacheCacheManager cacheCacheManager;

    @GetMapping(value = "/cache")
    public String cache(Model model) {
        Collection<String> names = cacheCacheManager.getCacheNames();
        List list = new ArrayList();
        List<Statistics> statisticsList = new ArrayList<>();
        for (String name : names) {
            Cache cache = cacheCacheManager.getCache(name);
            if (cache instanceof EhCacheCache) {
                EhCacheCache ehCacheCache = (EhCacheCache) cache;
                if (ehCacheCache == null) {
                    continue;
                }
                List ls = ehCacheCache.getNativeCache().getKeys();
                if (ls != null && ls.size() > 0) {
                    list.addAll(ls);
                }
                Statistics statistics = ehCacheCache.getNativeCache().getStatistics();
                if (statistics != null) {
                    statisticsList.add(statistics);
                }
            }
        }
        model.addAttribute("list", list);
        model.addAttribute("statisticsList", statisticsList);
        return getView("cache");
    }

}
